<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Courier New:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="JavaScript," />





  <link rel="alternate" href="/atom.xml" title="Never_yu's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon/favicon.ico?v=5.0.1" />






<meta name="description" content="在 JavaScript 中，函数中的 this 指向，很多同学总是理不清楚【这必然会带来一些问题】。确实，JavaScript 中，函数的 this 指向比较复杂多变。它和你调用的方式有关系，和 严格模式 或者 非严格模式 有关系，和你是否使用了箭头函数有关系，和你在使用函数时是否传入了 this 有关系，和你是否主动修改了调用对象有关系。


在绝大多数情况下，函数的调用方式决定了 this">
<meta property="og:type" content="article">
<meta property="og:title" content="关于 JavaScript 中 this 的详细总结">
<meta property="og:url" content="https://neveryu.github.io/2018/06/01/js-this/index.html">
<meta property="og:site_name" content="Never_yu's Blog">
<meta property="og:description" content="在 JavaScript 中，函数中的 this 指向，很多同学总是理不清楚【这必然会带来一些问题】。确实，JavaScript 中，函数的 this 指向比较复杂多变。它和你调用的方式有关系，和 严格模式 或者 非严格模式 有关系，和你是否使用了箭头函数有关系，和你在使用函数时是否传入了 this 有关系，和你是否主动修改了调用对象有关系。


在绝大多数情况下，函数的调用方式决定了 this">
<meta property="og:updated_time" content="2018-06-17T09:27:00.105Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="关于 JavaScript 中 this 的详细总结">
<meta name="twitter:description" content="在 JavaScript 中，函数中的 this 指向，很多同学总是理不清楚【这必然会带来一些问题】。确实，JavaScript 中，函数的 this 指向比较复杂多变。它和你调用的方式有关系，和 严格模式 或者 非严格模式 有关系，和你是否使用了箭头函数有关系，和你在使用函数时是否传入了 this 有关系，和你是否主动修改了调用对象有关系。


在绝大多数情况下，函数的调用方式决定了 this">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"hide"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: undefined,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="https://neveryu.github.io/2018/06/01/js-this/"/>


<!-- 网页加载条 -->
<script src="/js/src/pace.min.js"></script>
  <title> 关于 JavaScript 中 this 的详细总结 | Never_yu's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">Never_yu's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">认真的人才有资格开玩笑</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-guestbook">
          <a href="/guestbook" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-commenting"></i> <br />
            
            留言
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-example">
          <a href="/example" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            示例
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
      
      
        <li class="menu-item"> <a title="把这个链接拖到你的工具栏中,任何网页都可以High" href='javascript:(
/*
 * Copyright (C) 2016 Never_yu (Neveryu.github.io) <React.dong.yu@gmail.com>
 * Sina Weibo (http://weibo.com/Neveryu)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function go() {

var songs = [
  "http://dl.stream.qqmusic.qq.com/C400001Qu4I30eVFYb.m4a?vkey=2127178E4405E7B8B268F20F05232485735CCF4FF8C1432F0360D2626D0B6C9564B5627C7AB481BBC685FEDB0946A50E97C66F0D1B008226&guid=7175649092&uin=0&fromtag=66",
  "",
  "",
  ""
];

function c() {
  var e = document.createElement("link");
  e.setAttribute("type", "text/css");
  e.setAttribute("rel", "stylesheet");
  e.setAttribute("href", f);
  e.setAttribute("class", l);
  document.body.appendChild(e)
}

function h() {
  var e = document.getElementsByClassName(l);
  for (var t = 0; t < e.length; t++) {
    document.body.removeChild(e[t])
  }
}

function p() {
  var e = document.createElement("div");
  e.setAttribute("class", a);
  document.body.appendChild(e);
  setTimeout(function() {
    document.body.removeChild(e)
  }, 100)
}

function d(e) {
  return {
    height : e.offsetHeight,
    width : e.offsetWidth
  }
}

function v(i) {
  var s = d(i);
  return s.height > e && s.height < n && s.width > t && s.width < r
}

function m(e) {
  var t = e;
  var n = 0;
  while (!!t) {
    n += t.offsetTop;
    t = t.offsetParent
  }
  return n
}

function g() {
  var e = document.documentElement;
  if (!!window.innerWidth) {
    return window.innerHeight
  } else if (e && !isNaN(e.clientHeight)) {
    return e.clientHeight
  }
  return 0
}

function y() {
  if (window.pageYOffset) {
    return window.pageYOffset
  }
  return Math.max(document.documentElement.scrollTop, document.body.scrollTop)
}

function E(e) {
  var t = m(e);
  return t >= w && t <= b + w
}

function S() {
  var e = document.getElementById("audio_element_id");
  if(e != null){
    var index = parseInt(e.getAttribute("curSongIndex"));
    if(index > songs.length - 2) {
      index = 0;
    } else {
      index++;
    }
    e.setAttribute("curSongIndex", index);
    N();
  }

  e.src = i;
  e.play()
}

function x(e) {
  e.className += " " + s + " " + o
}

function T(e) {
  e.className += " " + s + " " + u[Math.floor(Math.random() * u.length)]
}

function N() {
  var e = document.getElementsByClassName(s);
  var t = new RegExp("\\b" + s + "\\b");
  for (var n = 0; n < e.length; ) {
    e[n].className = e[n].className.replace(t, "")
  }
}

function initAudioEle() {
  var e = document.getElementById("audio_element_id");
  if(e === null){
    e = document.createElement("audio");
    e.setAttribute("class", l);
    e.setAttribute("curSongIndex", 0);
    e.id = "audio_element_id";
    e.loop = false;
    e.bgcolor = 0;
    e.addEventListener("canplay", function() {
      setTimeout(function() {
        x(k)
      }, 500);
      setTimeout(function() {
        N();
        p();
        for (var e = 0; e < O.length; e++) {
          T(O[e])
        }
      }, 15500)
    }, true);
    e.addEventListener("ended", function() {
      N();
      h();
      go();
    }, true);
    e.innerHTML = " <p>If you are reading this, it is because your browser does not support the audio element. We recommend that you get a new browser.</p> <p>";
    document.body.appendChild(e);
  }
}

initAudioEle();
var e = 30;
var t = 30;
var n = 350;
var r = 350;

var curSongIndex = parseInt(document.getElementById("audio_element_id").getAttribute("curSongIndex"));
var i = songs[curSongIndex];

var s = "mw-harlem_shake_me";
var o = "im_first";
var u = ["im_drunk", "im_baked", "im_trippin", "im_blown"];
var a = "mw-strobe_light";

/* harlem-shake-style.css，替换成你的位置，也可以直接使用：//s3.amazonaws.com/moovweb-marketing/playground/harlem-shake-style.css */
var f = "//s3.amazonaws.com/moovweb-marketing/playground/harlem-shake-style.css";

var l = "mw_added_css";
var b = g();
var w = y();
var C = document.getElementsByTagName("*");
var k = null;
for (var L = 0; L < C.length; L++) {
  var A = C[L];
  if (v(A)) {
    if (E(A)) {
      k = A;
      break
    }
  }
}
if (A === null) {
  console.warn("Could not find a node of the right size. Please try a different page.");
  return
}
c();
S();
var O = [];
for (var L = 0; L < C.length; L++) {
  var A = C[L];
  if (v(A)) {
    O.push(A)
  }
}
})()'><i class="menu-item-icon fa fa-music fa-fw"></i> High一下</a></li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search fa-lg"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                关于 JavaScript 中 this 的详细总结
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2018-06-01T03:25:24+08:00" content="2018-06-01">
              2018-06-01
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/前端/" itemprop="url" rel="index">
                    <span itemprop="name">前端</span>
                  </a>
                </span>

                
                

              
            </span>
          

          

          

          
          

          
              &nbsp; | &nbsp;
              <span class="page-pv">热度
              <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>℃
              </span>
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p id="div-border-top-blue">在 JavaScript 中，函数中的 this 指向，很多同学总是理不清楚【这必然会带来一些问题】。确实，JavaScript 中，函数的 this 指向比较复杂多变。它和你调用的方式有关系，和 <strong>严格模式</strong> 或者 <strong>非严格模式</strong> 有关系，和你是否使用了箭头函数有关系，和你在使用函数时是否传入了 this 有关系，和你是否主动修改了调用对象有关系。</p>

<ul>
<li>在绝大多数情况下，函数的调用方式决定了 <code>this</code> 的值。<code>this</code> 不能再执行期间被赋值，并且在每次函数被调用时 <code>this</code> 的值也可能会不同。<code>ES5</code> 引入了 <code>bind</code> 方法来设置函数的 <code>this</code> 值，<a href="https://blog.csdn.net/csdn_yudong/article/details/78730844" target="_blank" rel="external">关于bind和call可以看我的文章</a>，而不用考虑函数如何被调用的，<code>ES2015</code> 引入了支持 <code>this</code> 词法解析的箭头函数（它在闭合的执行上下文内设置 <code>this</code> 的值）。</li>
</ul>
<ul>
<li>与其他语言相比，<strong>函数的 <code>this</code> 关键字</strong>在 <code>JavaScript</code> 中的表现略有不同，此外，在 严格模式 和 非严格模式之间也会有一些差别。</li>
</ul>
<a id="more"></a>
<h2 id="全局上下文"><a href="#全局上下文" class="headerlink" title="全局上下文"></a>全局上下文</h2><p>无论是否在严格模式下，在全局执行上下文中（在任何函数体外部）<code>this</code> 都指代全局对象。【在全局执行上下文中 <code>this</code> 都是全局对象 <code>window</code>】（浏览器环境）<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">1</span>;</span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">this</span>);    <span class="comment">// window</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">this</span>.a);  <span class="comment">// 1</span></span><br><span class="line"></span><br><span class="line"><span class="meta">"use strict"</span>;</span><br><span class="line"><span class="keyword">var</span> b = <span class="number">2</span>;</span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">this</span>);    <span class="comment">// window</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">this</span>.b);  <span class="comment">// 2</span></span><br></pre></td></tr></table></figure></p>
<h2 id="函数上下文"><a href="#函数上下文" class="headerlink" title="函数上下文"></a>函数上下文</h2><p>在函数内部，<code>this</code> 的值取决于函数被调用的方式。【取决于被调用的方式】</p>
<h3 id="简单调用"><a href="#简单调用" class="headerlink" title="简单调用"></a>简单调用</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f1</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 在浏览器中</span></span><br><span class="line">f1() === <span class="built_in">window</span>;  <span class="comment">// 在浏览器中，全局对象是widnow</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 在 Node 中</span></span><br><span class="line">f1() === global;</span><br></pre></td></tr></table></figure>
<p>【在严格模式下，<code>this</code> 将保持他进入执行上下文时的值】</p>
<p>在严格模式下，<code>this</code> 将保持他进入执行上下文时的值，所以下面的 <code>this</code> 将会默认为 <code>undefined</code>。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f2</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line"><span class="meta">  "use strict"</span>; <span class="comment">// 这里是严格模式</span></span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br><span class="line">f2() === <span class="literal">undefined</span>; <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<p>所以，在严格模式下，如果 <code>this</code> 没有被执行上下文（execution context）定义，那它将保持为 <code>undefined</code>。</p>
<p>因为 <code>f2()</code> 是被直接调用的，而不是作为对象的属性或方法调用的（如<code>window.f2()</code>）。有一些浏览器最初在支持严格模式时没有正确实现这个功能，于是它们错误的返回了 <code>window</code> 对象。</p>
<p>但是，如果用 <code>window</code> 来调用的话，<code>this</code> 就是 <code>window</code> 了。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f2</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line"><span class="meta">  "use strict"</span>; <span class="comment">// 这里是严格模式</span></span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(<span class="built_in">window</span>.f2())  <span class="comment">// window</span></span><br></pre></td></tr></table></figure></p>
<p>如果要想把 <code>this</code> 的值从一个上下文传到另一个，就要用 <code>call</code> 或者 <code>apply</code> 方法。</p>
<p>当一个函数在其主体中使用 <code>this</code> 关键字时，可以通过使用函数继承自 <code>Function.prototype</code> 的 <code>call</code> 或 <code>apply</code> 方法将 <code>this</code> 值绑定到调用中的特定对象</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">c, d</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">this</span>.a + <span class="keyword">this</span>.b + c + d;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> o = &#123;<span class="attr">a</span>: <span class="number">1</span>, <span class="attr">b</span>: <span class="number">3</span>&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 第一个参数是作为‘this’使用的对象</span></span><br><span class="line"><span class="comment">// 后续参数作为参数传递给函数调用</span></span><br><span class="line">add.call(o, <span class="number">5</span>, <span class="number">7</span>); <span class="comment">// 1 + 3 + 5 + 7 = 16</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 第一个参数也是作为‘this’使用的对象</span></span><br><span class="line"><span class="comment">// 第二个参数是一个数组，数组里的元素用作函数调用中的参数</span></span><br><span class="line">add.apply(o, [<span class="number">10</span>, <span class="number">20</span>]); <span class="comment">// 1 + 3 + 10 + 20 = 34</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>使用 <code>call</code> 和 <code>apply</code> 函数的时候要注意，如果传递给 <code>this</code> 的值不是一个对象，<code>JavaScript</code> 会尝试使用内部 <code>ToObject</code> 操作将其转换为对象。</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">因此，如果传递的值是一个原始值比如 <span class="number">7</span> 或 <span class="string">'foo'</span>，那么就会使用相关构造函数将它转换为对象，所以原始值 <span class="number">7</span> 会被转为对象，像 </span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Number</span>(<span class="number">7</span>) 这样，而字符串 <span class="string">'foo'</span> 转化成 <span class="keyword">new</span> <span class="built_in">String</span>(<span class="string">'foo'</span>) 这样。</span><br></pre></td></tr></table></figure>
<h2 id="bind-方法"><a href="#bind-方法" class="headerlink" title="bind 方法"></a>bind 方法</h2><p><code>ECMAScript 5</code> 引入了 <code>Function.prototype.bind</code>。调用 <code>f.bind(someObject)</code> 会 <strong>创建</strong>一个与 <code>f</code> 具有相同函数体和作用域的函数，但是在这个新函数中，<code>this</code> 将永久地被绑定到了 <code>bind</code> 的第一个参数，无论这个函数是如何被调用的。</p>
<p>【<code>this</code> 将永久的被绑定到了 <code>bind</code> 的第一个参数，无论这个函数是如何被调用的】</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">this</span>.a;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> g = f.bind(&#123;<span class="attr">a</span>:<span class="string">"azerty"</span>&#125;);</span><br><span class="line"><span class="built_in">console</span>.log(g()); <span class="comment">// azerty</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> h = g.bind(&#123;<span class="attr">a</span>:<span class="string">'yoo'</span>&#125;); <span class="comment">// bind只生效一次！</span></span><br><span class="line"><span class="built_in">console</span>.log(h()); <span class="comment">// azerty</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> o = &#123;<span class="attr">a</span>:<span class="number">37</span>, <span class="attr">f</span>:f, <span class="attr">g</span>:g, <span class="attr">h</span>:h&#125;;</span><br><span class="line"><span class="built_in">console</span>.log(o.f(), o.g(), o.h()); <span class="comment">// 37, azerty, azerty</span></span><br></pre></td></tr></table></figure>
<h2 id="箭头函数"><a href="#箭头函数" class="headerlink" title="箭头函数"></a>箭头函数</h2><p>在箭头函数中，<code>this</code> 与封闭词法上下文的 <code>this</code> 保持一致。在全局代码中，它将被设置为全局对象。【封闭词法上下文 是什么意思，你知道吗？】<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> foo = <span class="function">(<span class="params">(</span>) =&gt;</span> <span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 接着上面的代码</span></span><br><span class="line"><span class="comment">// 作为对象的一个方法调用</span></span><br><span class="line"><span class="keyword">var</span> obj = &#123;<span class="attr">foo</span>: foo&#125;;</span><br><span class="line"><span class="built_in">console</span>.log(obj.foo() === <span class="built_in">window</span>); <span class="comment">// true</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 尝试使用call来设定this</span></span><br><span class="line"><span class="built_in">console</span>.log(foo.call(obj) === <span class="built_in">window</span>); <span class="comment">// true</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 尝试使用bind来设定this</span></span><br><span class="line">foo = foo.bind(obj);</span><br><span class="line"><span class="built_in">console</span>.log(foo() === <span class="built_in">window</span>); <span class="comment">// true</span></span><br></pre></td></tr></table></figure></p>
<p>【无论如何，<code>foo</code> 的 <code>this</code> 被设置为<strong>他被创建时的上下文</strong>（在上面的例子中，就是全局对象）】<br>这同样适用于在其他函数内创建的箭头函数：这些箭头函数的 <code>this</code> 被设置为封闭的词法上下文的。</p>
<h2 id="作为对象的方法"><a href="#作为对象的方法" class="headerlink" title="作为对象的方法"></a>作为对象的方法</h2><blockquote>
<p>当函数作为对象里的方法被调用时，它们的 <code>this</code> 是调用该函数的对象</p>
</blockquote>
<p><code>this</code> 的绑定只受最靠近的成员引用的影响。在下面的例子中，我们把一个方法 <code>g</code> 当做对象 <code>o.b</code> 的函数调用。在这次执行期间，函数中的 <code>this</code> 将指向 <code>o.b</code> 。事实证明，这与他是对象 <code>o</code> 的成员没有多大关系，最靠近的引用才是最重要的。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">o.b = &#123; <span class="attr">g</span>: independent, <span class="attr">prop</span>: <span class="number">42</span> &#125;</span><br><span class="line"><span class="built_in">console</span>.log(o.b.g())</span><br></pre></td></tr></table></figure></p>
<h2 id="原型链中的-this"><a href="#原型链中的-this" class="headerlink" title="原型链中的 this"></a>原型链中的 <code>this</code></h2><p>对于在对象原型链上某处定义的方法，同样的概念也适用。如果该方法存在于一个对象的原型链上，那么 <code>this</code> 指向的是调用这个方法的对象，就像该方法在对象上一样。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> o = &#123;</span><br><span class="line">  f: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; </span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.a + <span class="keyword">this</span>.b; </span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">var</span> p = <span class="built_in">Object</span>.create(o);</span><br><span class="line">p.a = <span class="number">1</span>;</span><br><span class="line">p.b = <span class="number">4</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(p.f()); <span class="comment">// 5</span></span><br></pre></td></tr></table></figure>
<p>在这个例子中，对象 <code>p</code> 没有属于它自己的 <code>f</code> 属性，它的 <code>f</code> 属性继承自它的原型。虽然在对 <code>f</code> 的查找过程中，最终是在 <code>o</code> 中找到 <code>f</code> 属性的，这并没有关系；查找过程首先从 <code>p.f</code> 的引用开始，所以函数中的 <code>this</code> 指向 <code>p</code>。也就是说，因为 <code>f</code> 是作为 <code>p</code> 的方法调用的，所以它的 <code>this</code> 指向了 <code>p</code> 。这是 <code>JavaScript</code> 的原型继承中的一个有趣的特性。</p>
<h2 id="作为构造函数"><a href="#作为构造函数" class="headerlink" title="作为构造函数"></a>作为构造函数</h2><p>当一个函数用作构造函数时（适用 <code>new</code> 关键字），它的 <code>this</code> 被绑定到正在构造的新对象。</p>
<p>虽然构造器返回的默认值是 <code>this</code> 所指的那个对象，但它仍可以手动返回其他的对象（如果返回值不是一个对象，则返回 <code>this</code> 对象）</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 构造函数这样工作:</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * function MyConstructor()&#123;</span></span><br><span class="line"><span class="comment"> *   // 函数实体写在这里</span></span><br><span class="line"><span class="comment"> *   // 根据需要在this上创建属性，然后赋值给它们，比如：</span></span><br><span class="line"><span class="comment"> *   this.fum = "nom";</span></span><br><span class="line"><span class="comment"> *   // 等等...</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> *   // 如果函数具有返回对象的return语句，</span></span><br><span class="line"><span class="comment"> *   // 则该对象将是 new 表达式的结果。 </span></span><br><span class="line"><span class="comment"> *   // 否则，表达式的结果是当前绑定到 this 的对象。</span></span><br><span class="line"><span class="comment"> *   //（即通常看到的常见情况）。</span></span><br><span class="line"><span class="comment"> * &#125;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">C</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.a = <span class="number">37</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> o = <span class="keyword">new</span> C();</span><br><span class="line"><span class="built_in">console</span>.log(o.a); <span class="comment">// 37</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">C2</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.a = <span class="number">37</span>;</span><br><span class="line">  <span class="keyword">return</span> &#123;<span class="attr">a</span>:<span class="number">38</span>&#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">o = <span class="keyword">new</span> C2();</span><br><span class="line"><span class="built_in">console</span>.log(o.a); <span class="comment">// 38</span></span><br></pre></td></tr></table></figure>
<p>在刚刚的例子中（C2），因为在调用构造函数的过程中，手动的设置了返回对象，与 <code>this</code> 绑定的默认对象被丢弃了。（这基本上使得语句 <code>this.a = 37;</code> 成了“僵尸”代码，实际上并不是真正的“僵尸”，这条语句执行了，但是对于外部没有任何影响，因此完全可以忽略它）。</p>
<h2 id="作为一个-DOM-事件处理函数"><a href="#作为一个-DOM-事件处理函数" class="headerlink" title="作为一个 DOM 事件处理函数"></a>作为一个 DOM 事件处理函数</h2><blockquote>
<p>当函数被用作事件处理函数时，它的 <code>this</code> 指向触发事件的元素（一些浏览器在使用非 <code>addEventListener</code> 的函数动态添加监听函数时不遵守这个约定）。</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 被调用时，将关联的元素变成蓝色</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">bluify</span>(<span class="params">e</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="keyword">this</span> === e.currentTarget); <span class="comment">// 总是 true</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// 当 currentTarget 和 target 是同一个对象时为 true</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="keyword">this</span> === e.target);        </span><br><span class="line">  <span class="keyword">this</span>.style.backgroundColor = <span class="string">'#A5D9F3'</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 获取文档中的所有元素的列表</span></span><br><span class="line"><span class="keyword">var</span> elements = <span class="built_in">document</span>.getElementsByTagName(<span class="string">'*'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 将bluify作为元素的点击监听函数，当元素被点击时，就会变成蓝色</span></span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span> ; i&lt;elements.length ; i++)&#123;</span><br><span class="line">  elements[i].addEventListener(<span class="string">'click'</span>, bluify, <span class="literal">false</span>);</span><br></pre></td></tr></table></figure>
<h2 id="作为一个内联事件处理函数"><a href="#作为一个内联事件处理函数" class="headerlink" title="作为一个内联事件处理函数"></a>作为一个内联事件处理函数</h2><blockquote>
<p>当代码被内联 <code>on-event</code> 处理函数 调用时，它的 <code>this</code> 指向监听器所在的 <code>DOM</code> 元素</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">onclick</span>=<span class="string">"alert(this.tagName.toLowerCase());"</span>&gt;</span></span><br><span class="line">  Show this</span><br><span class="line"><span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>上面的 <code>alert</code> 会显示 <code>button</code> 。注意只有外层代码中的 <code>this</code> 是这样设置的：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">onclick</span>=<span class="string">"alert((function()&#123;return this&#125;)());"</span>&gt;</span></span><br><span class="line">  Show inner this</span><br><span class="line"><span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>在这种情况下，没有设置内部函数的 <code>this</code>，所以它指向 <code>global/window</code> 对象（即非严格模式下调用的函数未设置 <code>this</code> 时指向的默认对象）。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

<blockquote class="blockquote-center" style="color: #ccc;">
    -------------本文结束 <i class="fa fa-apple"></i> 感谢您的阅读-------------
</blockquote>

  <span id="inline-green" style="border-radius:3px;">作者</span>：<a class="link-blue" href="https://github.com/Neveryu" target="_blank">Neveryu</a><br/>有问题请 <a class="link-blue" href="https://neveryu.github.io/guestbook" target="_blank">留言</a> 或者私信我的 <a class="link-blue" href="http://weibo.com/Neveryu" target="_blank">微博</a>。

  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>满分是10分的话，这篇文章你给几分</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/reward/reward_wechat.png" alt="Never_yu WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/reward/reward_alipay.png" alt="Never_yu Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/JavaScript/" rel="tag"><i class="fa fa-tag"></i> JavaScript</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/05/01/vue-music/" rel="next" title="vue2.x 做一个音乐app">
                <i class="fa fa-chevron-left"></i> vue2.x 做一个音乐app
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/06/18/vue-prerender/" rel="prev" title="Vue 服务端渲染 or 预渲染">
                Vue 服务端渲染 or 预渲染 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>


          </div>
          


          
        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/avatar/avatar.png"
               alt="Never_yu" />
          <p class="site-author-name" itemprop="name">Never_yu</p>
          <p class="site-description motion-element" itemprop="description">Stay Hungry,Stay Foolish</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">36</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">19</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/Neveryu" target="_blank" title="Github">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  Github
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/Neveryu" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
          
        </div>

        
        
          <div class="cc-license motion-element" itemprop="license">
            <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
              <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
            </a>
          </div>
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="https://codeigniter.org.cn/" title="CodeIgniter中国" target="_blank">CodeIgniter中国</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="/weblog" title="建站日志" target="_blank">建站日志</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.csdn.net/csdn_yudong" title="CSDN" target="_blank">CSDN</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://neveryu.github.io/neveryu" title="个人首页" target="_blank">个人首页</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="/reward" title="打赏" target="_blank">打赏</a>
                </li>
              
            </ul>
          </div>
        
      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#全局上下文"><span class="nav-number">1.</span> <span class="nav-text">全局上下文</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#函数上下文"><span class="nav-number">2.</span> <span class="nav-text">函数上下文</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#简单调用"><span class="nav-number">2.1.</span> <span class="nav-text">简单调用</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#bind-方法"><span class="nav-number">3.</span> <span class="nav-text">bind 方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#箭头函数"><span class="nav-number">4.</span> <span class="nav-text">箭头函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#作为对象的方法"><span class="nav-number">5.</span> <span class="nav-text">作为对象的方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#原型链中的-this"><span class="nav-number">6.</span> <span class="nav-text">原型链中的 this</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#作为构造函数"><span class="nav-number">7.</span> <span class="nav-text">作为构造函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#作为一个-DOM-事件处理函数"><span class="nav-number">8.</span> <span class="nav-text">作为一个 DOM 事件处理函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#作为一个内联事件处理函数"><span class="nav-number">9.</span> <span class="nav-text">作为一个内联事件处理函数</span></a></li></ol></div>
            
          </div>
        </section>
      

      
        <section style="border-top:1px dotted #ccc; padding-top:10px;">
          <iframe width="100%" height="120" class="share_self"  frameborder="0" scrolling="no" src="https://widget.weibo.com/weiboshow/index.php?language=&width=0&height=120&fansRow=2&ptype=1&speed=0&skin=5&isTitle=1&noborder=1&isWeibo=0&isFans=0&uid=5346488237&verifier=d529ff3a&dpc=1"></iframe>
        </section>
      
    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        

<div class="busuanzi-count">

  <!-- <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script> -->
  <!-- 上面这个是之前的，不知道为什么失效了，改成下面这个 -->
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">您是第<span class="busuanzi-value" id="busuanzi_value_site_uv"></span>个小伙伴</span>
  

  
    <span class="site-pv">本站总浏览<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>次</span>
  
  
</div>



        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Never_yu</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io" rel="external nofollow">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">
    NexT.Pisces
  </a>
</div>

<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count" style="color: #e90f92;">全站共 156k 字</span>
</div>
        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });

                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  
<script type="text/javascript" async src="//push.zhanzhang.baidu.com/push.js">
</script>


  <!-- 按需加载背景 -->
  <!-- 背景动画 -->
<script type="text/javascript">
  // 按需加载背景
  // 如果是all，就直接加载了
  if("pc" == "all") {
    $.getScript("/js/src/particle.js?v=5.0.1");
  }
  // 识别手机或电脑的js开始
  (function(){
    var res = GetRequest();
    var par = res['index'];
    if(par!='gfan'){
      var ua=navigator.userAgent.toLowerCase();
      var contains=function (a, b){
          if(a.indexOf(b)!=-1){return true;}
      };
      if((contains(ua,"android") && contains(ua,"mobile"))||(contains(ua,"android") && contains(ua,"mozilla"))||(contains(ua,"android") && contains(ua,"opera"))||contains(ua,"ucweb7")||contains(ua,"iphone")){
        return false;
      } else {
        $.getScript("/js/src/particle.js?v=5.0.1");
      }
    }
  })();
  function GetRequest() {
    var url = location.search;
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
      var str = url.substr(1);
      strs = str.split("&");
      for(var i = 0; i < strs.length; i ++) {
        theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
      }
    }
    return theRequest;
  }
</script>
<!-- 识别手机或电脑的js结束 -->  

  <!-- 页面点击小红心 -->
  <!-- 页面点击小红心 -->

  <script type="text/javascript" src="/js/src/love.js?v=5.0.1"></script>


  <!-- 鼠标移动，效果 -->
  <!-- 鼠标移动特效 -->

  <script type="text/javascript" src="/js/src/jquery-stars.js?v=5.0.1"></script>
  <script type="text/javascript">
  jQuery('body').jstars({
  	image_path: '/images',
  	image: 'candy-cane-stars.png',
  	style: 'white',
  	width: 34,
  	height: 34,
  	delay: 700,
  	frequency: 5
  });
  </script>


  <!-- 页面 title 进入/离开 效果 -->

  <script type="text/javascript">var OriginTitile=document.title,st;document.addEventListener("visibilitychange",function(){document.hidden?(document.title="≡[。。]≡ 回不去了吗？!",clearTimeout(st)):(document.title="(ฅ>ω<*ฅ) Thank Vue~ "+OriginTitile,st=setTimeout(function(){document.title=OriginTitile},4e3))})</script>


</body>
</html>
